package com.hb.trade.server.project.notice.manager;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import com.hb.core.pojo.enums.CommonTypeEnum;
import com.hb.core.pojo.enums.DeployStatusEnum;
import com.hb.core.pojo.enums.NoticeNatureEnum;
import com.hb.core.pojo.parent.MPCommonEntity;
import com.hb.core.pojo.project.notice.dto.NoticeDTO;
import com.hb.core.pojo.project.notice.entity.Notice;
import com.hb.core.pojo.project.notice.entity.NoticeBidSection;
import com.hb.core.pojo.project.section.dto.BidSectionDTO;
import com.hb.trade.server.project.notice.service.NoticeBidSectionService;
import com.hb.trade.server.project.notice.service.NoticeService;
import com.hb.trade.server.project.notice.service.TenderInviteEnterpriseService;
import com.hb.trade.server.project.section.service.raw.BidSectionService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @Description: 首次公告及实现逻辑
 **/
@Slf4j
@Service
public class NoticeSaveFirst extends NoticeSaveSection {

    protected final BidSectionService bidSectionService;
    protected final NoticeBidSectionService noticeBidSectionService;
    protected final TenderInviteEnterpriseService tenderInviteEnterpriseService;

    public NoticeSaveFirst(NoticeService noticeService,
                           BidSectionService bidSectionService,
                           NoticeBidSectionService noticeBidSectionService,
                           TenderInviteEnterpriseService tenderInviteEnterpriseService) {
        super(noticeService);
        this.bidSectionService = bidSectionService;
        this.noticeBidSectionService = noticeBidSectionService;
        this.tenderInviteEnterpriseService = tenderInviteEnterpriseService;
    }

    /**
     * 对公告执行保存
     * 1: 当公告状态是未发布时, 公告可以任意修改
     * 2: 无论公告当前发布状态是什么, 每个标段对应的首次公告只有一个
     *
     * @param noticeDTO
     * @return 保存公告结果, true: 保存成功, false: 保存失败
     */
    @Transactional
    @Override
    public boolean saveNotice(NoticeDTO noticeDTO) {
        // 标段信息
        List<BidSectionDTO> sections = noticeDTO.getBidSectionList();

        // 处理公告主体信息
        Long noticeId = noticeDTO.getId();
        if (noticeId != null) {
            DeployStatusEnum status = getStatus(noticeId);
            if (status == DeployStatusEnum.DEPLOYED) {
                log.warn("无法修改已发布的公告");
                return false;
            }

            Notice rawNotice = noticeService.getById(noticeId);
            noticeDTO.to(rawNotice);
            noticeService.updateById(rawNotice);
        } else {
            // 验证所选的标段有没有发过首次公告
            List<Long> sectionIds = CollUtil.map(sections, (item) -> item.getId(), true);
            List<Notice> notices = noticeService.findNoticeBySectionIds(sectionIds, NoticeNatureEnum.FIRST.getCode());
            if (CollUtil.isNotEmpty(notices)) {
                log.warn("所选标段中包含已发布过首次公告的标段");
                return false;
            }

            // 公告发布状态默认为未发布
            noticeDTO.setDeployStatus(DeployStatusEnum.UN_DEPLOYED.getCode());
            noticeDTO.buildBaseData(1);
            noticeService.save(noticeDTO);
        }

//        // 更新每个标段的标书售价和系统使用费
//        for (BidSectionDTO section : sections) {
//            bidSectionService.saveOrUpdate(section);
//        }

        // 处理公告跟标段的关联
        List<Long> sectionIds = CollUtil.map(sections, MPCommonEntity::getId, true);

        // 验证所选标段是否已经发布过首次公告
        // boolean result = noticeBidSectionService.existsFirstNotice(sectionIds);
        // if (result) {
        //     throw new RuntimeException("选择的标段已经发布过首次公告");
        // }
        // FIXME 点击发布公告的时候判断是否发布过首次公告

        if (CollUtil.isNotEmpty(sectionIds)) {
            // 更新标段, 公告中间表
            noticeBidSectionService.updateNoticeSections(noticeDTO.getId(), sectionIds);
        }

        // 判断是公开的还是邀请的  如果是邀请的需要更新邀请企业信息
        if (null != noticeDTO.getCommonType() && noticeDTO.getCommonType() == CommonTypeEnum.INVITE.getCode()) {
            tenderInviteEnterpriseService.updateInviteEnterprise(noticeDTO);
        }
        return true;

        //设置项目id
//        List<BidSectionDTO> bidSectionList = noticeDTO.getBidSectionList();
//        noticeDTO.setBidSectionList(bidSectionList);
//        if (noticeDTO.getProjectId() == null) {
//            BidSection bidSection = bidSectionService.getById(bidSectionList.get(0).getId());
//            noticeDTO.setProjectId(bidSection.getProjectId());
//        }
        //保存公告信息
//        boolean save = noticeService.saveNotice(noticeDTO);

        //TODO 保存项目信息(更新 采购概况及范围 采购条件  投标人资格要求 联合体投标)
//        projectService.updateNoticeProjectRelevant(project);

        //TODO 保存邀请人信息
//        if (invitationFlag) {
//            List<TenderInvite> tenderInviteList = new ArrayList<>();
//            QueryWrapper<TenderInvite> tenderInviteDtoQueryWrapper = new QueryWrapper<>();
//            List<TenderInviteDTO> tenderInviteDTOList = noticeAddDto.getTenderInviteDTOList();
//            for (TenderInviteDTO tenderInviteDto : tenderInviteDTOList) {
//                for (BidSectionDTO bidSectionDto : bidSectionList) {
//                    //如果企业id和标段id存在就不入库了
//                    boolean flag = tenderInviteService.findTenderInviteInfoByOrgIdAndSectionId(tenderInviteDto.getOrgId(), bidSectionDto.getId());
//                    if (flag){
//                        continue;
//                    }
//                    TenderInvite tenderInvite = new TenderInvite();
//                    tenderInvite.setId(IdUtil.getSnowflake(1, 1).nextId());
//                    tenderInvite.setSectionId(bidSectionDto.getId());
//                    tenderInvite.setOrgId(tenderInviteDto.getOrgId());
//                    tenderInvite.setNoticeId(noticeId);
//                    tenderInvite.setInviteStatus(InviteStatusEnum.FED_BACK.getCode());
//                    tenderInviteList.add(tenderInvite);
//                }
//            }
//            //先删除后加邀请人信息
//            QueryWrapper<TenderInvite> tenderInviteQueryWrapper = new QueryWrapper<>();
//            tenderInviteQueryWrapper.lambda().eq(TenderInvite::getNoticeId, noticeId);
//            tenderInviteService.remove(tenderInviteQueryWrapper);
//            tenderInviteService.saveBatch(tenderInviteList);
//        }
//        boolean notFixedFlag = Enums.equals(BondEnum.NOT_FIXED, noticeDTO.getGuaranteeFlag());//非固定金额
        // 更改标段状态和设置标段相关字段
//        for (BidSectionDTO bidSectionDto : bidSectionList) {
//            BidSectionManager sectionManager = bidSectionDto.to(BidSectionManager.class);
//            sectionManager.fillNoticeField(noticeDTO, notFixedFlag);
//            sectionManager.refreshBidSection();
//        }


//        NoticeAddDTO noticeAddDTO1 = new NoticeAddDTO();
//        NoticeDTO dto = new NoticeDTO();
//        dto.setId(noticeDTO.getId());
//        noticeAddDTO1.setNotice(dto);
//        return MsgUtil.success(noticeAddDTO1);
    }

    /**
     * @param notice:
     * @Description: 发布的逻辑修改 同步到标段信息
     * @Author: zhongdl
     * @Date:2022/1/13 11:31
     * @return: {@link String }
     **/
    @Override
    public String deploy(Notice notice) {
        List<NoticeBidSection> noticeBidSections = noticeBidSectionService.listNoticeBidSectionByNoticeId(notice.getId());
        if (CollUtil.isEmpty(noticeBidSections)) {
            return null;
        }
        BidSectionDTO sectionOptions = BeanUtil.copyProperties(notice.getSectionOptions(), BidSectionDTO.class);
        if (sectionOptions == null) {
            return null;
        }
        //如果不需要重新编制招标文件 更新招标文件的信息 则需要把公告的标段信息同步到标段中
        for (NoticeBidSection noticeBidSection : noticeBidSections) {
            sectionOptions.setId(noticeBidSection.getSectionId());
            bidSectionService.updateById(sectionOptions);
        }
        return null;
    }


}
